package com.example.elm.Home_Page;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.example.elm.First_Page.First_Page;
import com.example.elm.First_Page.Home_Page;
import com.example.elm.R;
import com.example.elm.SQL.Connection_SQL;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Set_Location_Page extends AppCompatActivity implements PoiSearch.OnPoiSearchListener {

    TextView city_text_view, my_location_text_view, add_address;
    LinearLayout add_my_set_location, add_set_nearby_location, re_set_location;

    String location = "", city = "", email = "", district = "";
    double lat, lng;
    private PoiSearch poisearch;
    boolean is_loading_my_location_data = false;
    List<String> nearby_location = new ArrayList<>();
    List<List<String>> my_location = new ArrayList<>();

    private class Loading_Nearby_Location_Thread extends Thread {
        @Override
        public void run() {
            LatLonPoint point = new LatLonPoint(lat, lng);
            PoiSearch.Query query = new PoiSearch.Query("", "", "");
            query.setPageSize(20);
            query.setPageNum(0);
            try {
                poisearch = new PoiSearch(Set_Location_Page.this, query);
            } catch (AMapException e) {
                throw new RuntimeException(e);
            }
            poisearch.setOnPoiSearchListener(Set_Location_Page.this);
            poisearch.setBound(new PoiSearch.SearchBound(point, 500, true));
            poisearch.searchPOIAsyn();

            while (nearby_location.isEmpty()) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    add_set_nearby_location.removeAllViews();
                    for (int i = 0; i < nearby_location.size(); i++) {
                        View view = LayoutInflater.from(Set_Location_Page.this).inflate(R.layout.set_nearby_location_view, null);
                        TextView address_aoi_name = view.findViewById(R.id.address_aoi_name);
                        address_aoi_name.setText(nearby_location.get(i));

                        add_set_nearby_location.addView(view);
                    }
                }
            });
        }
    }

    private class Loading_Location_Data_Thread extends Thread {
        @Override
        public void run() {
            is_loading_my_location_data = false;

            ExecutorService executorService = Executors.newSingleThreadExecutor();
            executorService.execute(() -> {
                try {
                    Connection_SQL userSQL = new Connection_SQL();
                    Connection connection = userSQL.connection();
                    String sql = "SELECT * FROM `" + email + "_user_location`";
                    PreparedStatement preparedStatement = connection.prepareStatement(sql);
                    ResultSet set = preparedStatement.executeQuery();
                    while (set.next()) {
                        List<String> temp = new ArrayList<>();
                        temp.add(set.getString("address"));
                        temp.add(set.getString("door_number"));
                        temp.add(set.getString("label"));
                        temp.add(set.getString("phone_number"));
                        temp.add(set.getString("name"));
                        if (set.getInt("is_sir") == 1) {
                            temp.add("先生");
                        }
                        else {
                            temp.add("女士");
                        }
                        temp.add(String.valueOf(set.getDouble("lat")));
                        temp.add(String.valueOf(set.getDouble("lng")));
                        temp.add(set.getString("district"));
                        temp.add(set.getString("city"));
                        temp.add(set.getString("province"));
                        my_location.add(temp);
                    }
                    is_loading_my_location_data = true;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            while (!is_loading_my_location_data) {
                try {
                    Thread.sleep(1);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    add_my_set_location.removeAllViews();
                    for (int i = 0; i < my_location.size(); i++) {
                        View view = LayoutInflater.from(Set_Location_Page.this).inflate(R.layout.my_location_view, null);
                        TextView address_aoi_name = view.findViewById(R.id.address_aoi_name);
                        TextView door_number = view.findViewById(R.id.door_number);
                        TextView name = view.findViewById(R.id.name);
                        TextView is_sir = view.findViewById(R.id.is_sir);
                        TextView phone_number = view.findViewById(R.id.phone_number);
                        LinearLayout is_set_label = view.findViewById(R.id.is_set_label);
                        TextView which_label = view.findViewById(R.id.which_label);
                        LinearLayout choose_this_location = view.findViewById(R.id.choose_this_location);

                        address_aoi_name.setText(my_location.get(i).get(0));
                        door_number.setText(my_location.get(i).get(1));
                        name.setText(my_location.get(i).get(4));
                        is_sir.setText(my_location.get(i).get(5));
                        phone_number.setText(my_location.get(i).get(3));

                        if (!my_location.get(i).get(2).isEmpty()) {
                            is_set_label.setVisibility(View.VISIBLE);
                            which_label.setText(my_location.get(i).get(2));
                        }

                        int finalI = i;
                        choose_this_location.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                Intent intent = new Intent(Set_Location_Page.this, Home_Page.class);
                                intent.putExtra("address", my_location.get(finalI).get(0));
                                intent.putExtra("district", my_location.get(finalI).get(8));
                                intent.putExtra("lat", Double.valueOf(my_location.get(finalI).get(6)));
                                intent.putExtra("lng", Double.valueOf(my_location.get(finalI).get(7)));
                                intent.putExtra("city", my_location.get(finalI).get(9));
                                intent.putExtra("province", my_location.get(finalI).get(10));
                                intent.putExtra("user_name", my_location.get(finalI).get(4));
                                intent.putExtra("user_sex", my_location.get(finalI).get(5));
                                intent.putExtra("user_phone_number", my_location.get(finalI).get(3));
                                setResult(1, intent);
                                finish();
                            }
                        });

                        add_my_set_location.addView(view);
                    }
                }
            });
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_location_page);

        location = getIntent().getStringExtra("location");
        city = getIntent().getStringExtra("city");
        email = getIntent().getStringExtra("email");
        lat = getIntent().getDoubleExtra("lat", 0);
        lng = getIntent().getDoubleExtra("lng", 0);
        district = getIntent().getStringExtra("district");

        add_my_set_location = findViewById(R.id.add_my_set_location);
        add_set_nearby_location = findViewById(R.id.add_set_nearby_location);
        city_text_view = findViewById(R.id.city);
        my_location_text_view = findViewById(R.id.my_location);
        re_set_location = findViewById(R.id.re_set_location);
        add_address = findViewById(R.id.add_address);

        add_my_set_location.addView(LayoutInflater.from(this).inflate(R.layout.load_data, null));
        add_set_nearby_location.addView(LayoutInflater.from(this).inflate(R.layout.load_data, null));

        city_text_view.setText(city);
        my_location_text_view.setText(location);

        Loading_Location_Data_Thread loadingLocationDataThread = new Loading_Location_Data_Thread();
        loadingLocationDataThread.start();

        Loading_Nearby_Location_Thread loadingNearbyLocationThread = new Loading_Nearby_Location_Thread();
        loadingNearbyLocationThread.start();

        city_text_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Set_Location_Page.this, Choose_City_Page.class);
                intent.putExtra("city_text", city);
                startActivityForResult(intent, 1);
            }
        });

        re_set_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        add_address.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Set_Location_Page.this, Add_New_Location.class);
                intent.putExtra("lat", lat);
                intent.putExtra("lng", lng);
                intent.putExtra("city", city);
                intent.putExtra("district", district);
                intent.putExtra("email", email);
                startActivityForResult(intent, 2);
            }
        });
    }

    @Override
    public void onPoiSearched(PoiResult poiResult, int resultCode) {
        if (resultCode == AMapException.CODE_AMAP_SUCCESS) {
            if (poiResult != null && poiResult.getPois().size() > 0) {
                List<PoiItem> poiItems = poiResult.getPois();
                for (PoiItem poiItem : poiItems) {
                    nearby_location.add(poiItem.getTitle());
                }
            } else {
                Toast.makeText(this, "无搜索结果", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(this, "搜索失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 1: {
                if (data != null) {
                    city_text_view.setText(data.getStringExtra("district_name"));
                }
            }

            case 2: {
                my_location.clear();
                Loading_Location_Data_Thread loadingLocationDataThread = new Loading_Location_Data_Thread();
                loadingLocationDataThread.start();
            }
        }
    }
}